package com.lemon.springcloud.core.util;

import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * Class Name: PropertiesUtils
 * Create Date: 18-3-22 下午1:53
 * Creator: lemon
 * Version: v1.0
 * Updater:
 * Date Time:
 * Description:
 */
public final class PropertiesUtils {

    private static final String LEMON_BOOT_DEFAULT_RESOURCE_LOCATION = "META-INF/lemon-default-config.properties";

    public static String getString(String key) {
        String value = "";
        try {
            Enumeration<URL> urls = ClassLoader.getSystemResources(LEMON_BOOT_DEFAULT_RESOURCE_LOCATION);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                value = properties.getProperty(key);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    public static Set<String> getPrefixSigns(String componentKey) {
        Set<String> signSet = new HashSet<String>();
        List<String> prefixKeys = new ArrayList<String>();

        try {
            Enumeration<URL> urls = ClassLoader.getSystemResources(LEMON_BOOT_DEFAULT_RESOURCE_LOCATION);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                if (null != properties) {
                    Set keySet = properties.keySet();
                    Iterator keyItor = keySet.iterator();
                    while (keyItor.hasNext()) {
                        String key = keyItor.next().toString();
                        if (key.contains(componentKey)) {
                            prefixKeys.add(key);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 处理
        if (prefixKeys.size() > 0) {
            prefixKeys.forEach(prefixKey -> {
                String subKey = prefixKey.substring(componentKey.length());
                signSet.add(subKey.substring(0, subKey.indexOf(".")));
            });
        }

        return signSet;
    }
}
